<?php

namespace app\common\api\controller;

use app\common\controller\Log;
use app\common\model\Levels;
use app\common\model\Member;
use app\common\model\MemberFinance;
use app\common\model\MemberPackages;
use app\common\model\Packages;
use think\Controller;
use think\Db;

final class Bonus extends Controller
{
    protected static $bonusRule = [];
    private static $uid = 0;
    private static $user = 0;
    private static $total = 0.00;

    public function __construct($uid, $total)
    {
        self::$uid = $uid;
        self::$user = Member::find($uid);
        self::$total = $total;
        self::$bonusRule = Db('BonusRule')->find();
    }

    /**
     * 会员激活
     * @param $uid
     * @return bool|int
     */
    private function active($uid)
    {
        $info = Db('member')->field('tuijianid')->find($uid);
        /* 激活用户需要更新字段，激活字段=1;*/
        $data['status'] = 1;
        $data['active_time'] = time();
        //激活用户
        $res1 = Db('member')->where('uid', $uid)->update($data);
        $res2 = Db('ucenter_member')->where('id', $uid)->setField('status', 1);

        if ($res1 && $res2) {
            Db('member')->where('uid', $info['tuijianid'])->setInc('recom_num', 1);
            return true;
        } else {
            return -103;//状态更改失败
        }
    }

    /**
     * 转积分
     * @return void
     */
    public function giveMoney()
    {
        $total1 = self::$bonusRule['total1'];
        $total2 = self::$bonusRule['total2'];
        $money_rate = self::$bonusRule['money_rate'];
        $stock_rate = self::$bonusRule['stock_rate'];
        $price = round($total1 / $total2, 2);
        $stockMoney = round((self::$total * $stock_rate) / $price, 2);
        $moneyMoney = self::$total * $money_rate;
//        write_log($price, 'ceshi');
//        write_log($stockMoney, 'ceshi');
        // 启动事务
        Db::startTrans();
        try {
            Db('bonus_rule')->where('id', 1)->setInc('total1', $moneyMoney);
            Db('bonus_rule')->where('id', 1)->setInc('total2', $stockMoney);

            Db('member_finance')->where('uid', self::$uid)->setInc('hasgreen', $stockMoney);
            $finance = Db('member_finance')->where('uid', self::$uid)->find();
            $type = array('recordtype' => 1, 'changetype' => 3, 'moneytype' => 3);
            $money = array('money' => $stockMoney, 'hasmoney' => $finance['hasgreen']);
            money_change($type, self::$uid, self::$uid, $money);
            unset($type, $money);

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
        }
    }

    /**
     * 增加封顶额度
     */
    public function addTopMoney()
    {
        
    }

    /**
     * 推荐级差奖
     * @return bool
     */
    public function bonusRecom()
    {
        $tinfos = Db('member')->field('uid,userrank,tuijianid,tuijianids')->where('uid', 'in', self::$user['tuijianids'])->order('tdeep desc')->select();
        if (!$tinfos) {
            return false;
        }

        $userrank = self::$user['userrank'];
        $rank = max(0, $userrank);
        $recomRateArr = user_level_bonus_format(self::$bonusRule['recom_rate']);
        $updateConditionArr = user_level_bonus_format(self::$bonusRule['update_condition']);
        $end = end($updateConditionArr);
//        write_log($recomRateArr, 'ceshi');
        foreach ($tinfos as $val) {
            if ($val['userrank'] > $rank) {
                $rate = $recomRateArr[$val['userrank']][2] - $recomRateArr[$rank][2];
//                write_log($rate, 'ceshi');
                $recomMoney = self::$total * $rate;
//                write_log($val['uid'] . '_' . $recomMoney, 'ceshi');
                if ($recomMoney > 0) {
                    self::bonusShare($recomMoney, 1, $val['uid'], self::$user);
                    // 最高级别享受平级奖
                    if ($val['userrank'] >= $end[1]) {
                        self::bonusPing($val, $recomMoney);
                    }
                    self::bonusHelp($val, $recomMoney);

                    $rank = $val['userrank'];
                }
            }
        }
    }

    /**
     * 推荐奖的平级奖
     * @param $user
     * @param $recomMoney
     * @return bool
     */
    public function bonusPing($user, $recomMoney)
    {
        $tinfo = Db('member')->field('uid,userrank')
            ->where('userrank', '=', $user['userrank'])
            ->where('uid', 'in', $user['tuijianids'])
            ->where('status', 1)
            ->order('tdeep desc')
            ->find();
        if (!$tinfo) {
            return false;
        }

        $pingMoney = $recomMoney * self::$bonusRule['ping_rate'];
        if ($pingMoney > 0) {
            self::bonusShare($pingMoney, 2, $tinfo['uid'], $user);
        }
    }

    /**
     * 幸运补贴
     * @return bool
     */
    public function bonusMember()
    {
        $uids = trim(self::$user['tuijianids'] . self::$uid, ',');
        $perTdeep = self::$bonusRule['per_tdeep'];
        $perMember = self::$bonusRule['per_member'];
        $minTdeep = self::$user['tdeep'] - $perTdeep;
        $minTdeep = max($minTdeep, 0);
        $tinfos = Db('member')->field('uid,userrank')
            ->where('tdeep', '>=', $minTdeep)
            ->where('tdeep', '<=', self::$user['tdeep'])
            ->where('uid', 'in', $uids)
            ->where('status', 1)
            ->order('tdeep desc')
            ->select();
        if (!$tinfos) {
            return false;
        }

        foreach ($tinfos as $val) {
            $members = Db('member')->where('id', '<', $val['uid'])->order('id desc')->limit($perMember)->select();
            if (!$members) {
                continue;
            }

            foreach ($members as $v) {
                if ($v['userrank'] <= 0) {
                    continue;
                }

                //已经发过的不再发了

                $memberMoney = self::$total * self::$bonusRule['member_rate'];
                if ($memberMoney > 0) {
                    self::bonusShare($memberMoney, 3, $v['uid'], self::$user);
                }
            }
        }
    }

    /**
     * 店铺补贴
     * @return bool
     */
    public function bonusStore()
    {
        $uids = trim(self::$user['tuijianids'], ',');
        $storeRate = self::$bonusRule['store_rate'];
        $tinfo = Db('member')->field('uid,userrank')
            ->where('is_store', 1)
            ->where('uid', 'in', $uids)
            ->where('userrank', '>=', 1)
            ->where('status', 1)
            ->order('tdeep desc')
            ->find();
        if (!$tinfo) {
            return false;
        }

        $storeMoney = self::$total * $storeRate;
        if ($storeMoney > 0) {
            self::bonusShare($storeMoney, 4, $tinfo['uid'], self::$user);
        }
    }

    /**
     * 感恩奖
     * @param $tinfo
     * @param $money
     * @return bool
     */
    public function bonusHelp($tinfo, $money)
    {
        $helpRate = self::$bonusRule['help_rate'];
        $sinfos = Db('member')->field('uid,userrank')
            ->where('tuijianid', $tinfo['uid'])
            ->where('userrank', '>=', 1)
            ->where('status', 1)
            ->select();
        if (!$sinfos) {
            return false;
        }

        $number = count($sinfos);
        $helpMoney = round(($money * $helpRate) / $number);
        if ($helpMoney > 0) {
            foreach ($sinfos as $val) {
                self::bonusShare($helpMoney, 5, $val['uid'], $tinfo);
            }
        }
    }

    /**
     * Notes:增加成长值
     * User: Administrator
     * Date: 2023/9/8
     * Time: 8:43
     * @return false
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function addAchievement()
    {
        $map = [
            'uid' => ['in', trim(self::$user->tuijianids, ',')],
            'status' => ['>=', 1],
        ];

        Db('member')->where($map)->setInc('achievement', self::$total);
    }

    /**
     * 会员级别更新
     */
    public function bonusUpdate()
    {
        self::$user->userrank = 1;
        self::$user->save();

        Db('rank_change_log')->insert(
            [
                'type' => 1,
                'updatetype' => 1,
                'recordtype' => 1,
                'uid' => self::$uid,
                'old' => 0,
                'new' => 1,
                'create_time' => time(),
                'update_time' => time(),
            ]
        );

        $map = [
            'uid' => ['in', trim(self::$user->tuijianids, ',')],
            'status' => ['>=', 1],
        ];
        $tinfos = Db('member')->where($map)->order('tdeep', 'desc')->select();
        if (!$tinfos) {
            return false;
        }
        $updateConditionArr = user_level_bonus_format(self::$bonusRule['update_condition']);
        $end = end($updateConditionArr);

//        write_log($end, 'ceshi');
        foreach ($tinfos as $val) {
            if ($val['userrank'] <= 0 || $val['userrank'] >= $end[1]) {
                continue;
            } elseif ($val['userrank'] == 1) {
                if ($val['achievement'] >= $updateConditionArr[2][2]) {
                    Db('member')->where('uid', $val['uid'])->setField('userrank', 2);
                    Db('rank_change_log')->insert(
                        [
                            'type' => 1,
                            'updatetype' => 1,
                            'recordtype' => 1,
                            'uid' => $val['uid'],
                            'old' => 1,
                            'new' => 2,
                            'create_time' => time(),
                            'update_time' => time(),
                        ]
                    );
                }
            } else {
                $num = 0;
                $sons = Db('member')->where('tuijianid', $val['uid'])->where('status', 1)->select();
                if (count($sons) < 2) {
                    continue;
                }
//                if ($val['uid'] == 15) {
//                    write_log($sons, 'ceshi');
//                }
                foreach ($sons as $item) {
                    if ($item['userrank'] >= $val['userrank']) {
                        $num += 1;
                        continue;
                    }

                    $where = [
                        'status' => 1,
                        'userrank' => ['egt', $val['userrank']],
                        'tuijianids' => ['like', $item['tuijianids'] . $item['uid'] . ',%']
                    ];

                    $count = Db('member')->where($where)->count();
//                    if ($val['uid'] == 15) {
//                        write_log(Db('member')->getLastSql(), 'ceshi');
//                    }
                    if ($count) {
                        $num += 1;
                    }
                }

//                if ($val['uid'] == 15) {
//                    write_log($num, 'ceshi');
//                    write_log($updateConditionArr[$val['userrank'] + 1][2], 'ceshi');
//                }
                if ($num >= $updateConditionArr[$val['userrank'] + 1][2]) {
                    Db('member')->where('uid', $val['uid'])->setField('userrank', ($val['userrank'] + 1));
                    Db('rank_change_log')->insert(
                        [
                            'type' => 1,
                            'updatetype' => 1,
                            'recordtype' => 1,
                            'uid' => $val['uid'],
                            'old' => $val['userrank'],
                            'new' => ($val['userrank'] + 1),
                            'create_time' => time(),
                            'update_time' => time(),
                        ]
                    );
                }
            }
        }
    }

    /**
     * 奖金生成
     * @param $bonusmoney
     * @param $changetype
     * @param $uid
     * @param $fromuser
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function bonusShare($bonusmoney, $changetype, $uid, $fromuser)
    {
        $map['uid'] = $uid;
        $user = Db('member_finance')->where($map)->find();

        $tax_rate = self::$bonusRule['tax_rate'];
        if ($tax_rate > 100 || $tax_rate <= 0) {
            $tax = 0;
        } else {
            $tax = $tax_rate * 0.01;
        }

//        $green_rate = self::$bonusRule['green_rate'];
//        if ($green_rate > 100 || $green_rate <= 0) {
//            $green = 0;
//        } else {
//            $green = $green_rate * 0.01;
//        }

        $tax_money = $bonusmoney * $tax;
//        $green_money = $bonusmoney * $green;
        $actulMoney = $bonusmoney - $tax_money;

        $data['hasmoney'] = $user['hasmoney'] + $actulMoney;
        $data['allmoney'] = $user['allmoney'] + $actulMoney;
//        if ($green_money) {
//            $data['hasgreen'] = $user['hasgreen'] + $green_money;
//            $data['allgreen'] = $user['allgreen'] + $green_money;
//        }

        $res = Db('member_finance')->where($map)->update($data);

        if ($res) {
            self::bonus('BonusCount', $changetype, $user, $bonusmoney, $actulMoney, $tax_money);
            self::bonus('BonusTotal', $changetype, $user, $bonusmoney, $actulMoney, $tax_money);

            $user = Db('member_finance')->where($map)->find();

            $type = array('recordtype' => 1, 'changetype' => $changetype, 'moneytype' => 2);
            $money = array('money' => $actulMoney, 'hasmoney' => $user['hasmoney'], 'tax_money' => $tax_money);
            money_change($type, $uid, $fromuser['uid'], $money);
            unset($type, $money);

//            if ($green_money) {
//                $type = array('recordtype' => 1, 'changetype' => $changetype, 'moneytype' => 4);
//                $money = array('money' => $green_money, 'hasmoney' => $user['hasgreen']);
//                money_change($type, $uid, $fromuser['uid'], $money);
//                unset($type, $money);
//            }

            finance2($changetype, $bonusmoney); //公司财务统计
        }
    }

    /**
     * @param $table
     * @param $bonustype
     * @param $touser
     * @param $money
     * @param $hasmoney
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    private function bonus($table, $bonustype, $touser, $money, $hasmoney, $tax_money)
    {
        if ($table == 'BonusCount' || $table == 'bonus_count') {
            $count_date = strtotime('today');
            $map['count_date'] = $count_date;
        } else {
            $count_date = time();
        }
        $BCount = Db($table);

        $map['userid'] = $touser['uid'];

        $bonusData = $BCount->where($map)->find();
        $field = 'bonus' . $bonustype;
        if ($bonusData) {
            $data[$field] = $bonusData[$field] + $money;
            $data['total'] = $bonusData['total'] + $hasmoney;
            $data['tax_money'] = $bonusData['tax_money'] + $tax_money;
            $BCount->where($map)->update($data);
        } else {
            $data = array(
                'userid' => $touser['uid'],
                'usernumber' => $touser['usernumber'],
                'count_date' => $count_date
            );
            $data[$field] = $money;
            $data['total'] = $hasmoney;
            $data['tax_money'] = $tax_money;
            $BCount->insert($data);
        }
    }
}